import { defineEventHandler, getQuery, readBody } from 'h3';

import { usePageResponseSuccess, useResponseError } from '../../utils/response';

// 生成补贴配置数据的辅助函数
function generateSubsidyConfigs() {
  const configs = [];
  const baseConfigId = 20_001;

  // 省内和省外的补贴配置
  const areaTypes = ['省内', '省外'];
  const areaTypeCodes = ['in', 'out'];

  // 生成30条数据
  for (let i = 0; i < 30; i++) {
    const areaTypeIndex = i % 2; // 交替生成省内和省外
    const areaType = areaTypes[areaTypeIndex];
    const areaTypeCode = areaTypeCodes[areaTypeIndex];

    // 每个区域类型只有1条启用状态
    const status = i % 10 === 0 ? '启用' : '停用'; // 每10条数据中有1条启用

    // 生成随机的补贴金额（2.00-5.00之间，保留2位小数）
    const subsidyAmount = Math.round((Math.random() * 3 + 2) * 100) / 100;

    // 生成随机的生效日期（近1年的不同月份）
    const year = 2023;
    const month = Math.floor(Math.random() * 12) + 1;
    const day = Math.floor(Math.random() * 28) + 1;
    const effectiveDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

    configs.push({
      configId: baseConfigId + i,
      areaType: areaTypeCode,
      areaTypeText: areaType,
      subsidyAmount,
      effectiveDate,
      status,
      statusText: status,
    });
  }

  return configs;
}

// 补贴配置数据模拟
const subsidyConfigs = generateSubsidyConfigs();

// 获取补贴配置列表
export const getSubsidyConfigsHandler = defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const page = Number.parseInt(query.page as string) || 1;
    const pageSize = Number.parseInt(query.pageSize as string) || 20;

    // 分页处理
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = subsidyConfigs.slice(startIndex, endIndex);

    return usePageResponseSuccess(page, pageSize, paginatedData, {
      message: '获取成功',
    });
  } catch {
    return useResponseError('获取失败');
  }
});

// 创建补贴配置
export const createSubsidyConfigHandler = defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);

    // 生成新的ID
    const newId =
      Math.max(...subsidyConfigs.map((item) => item.configId), 0) + 1;

    const newConfig = {
      configId: newId,
      areaType: body.areaType,
      areaTypeText: body.areaType === 'in' ? '省内' : '省外',
      subsidyAmount: Number.parseFloat(body.subsidyAmount),
      effectiveDate: body.effectiveDate,
      status: '启用', // 新创建的默认启用
      statusText: '启用',
    };

    subsidyConfigs.unshift(newConfig);

    return useResponseSuccess(newConfig);
  } catch {
    return useResponseError('创建失败');
  }
});

// 更新补贴配置状态
export const updateSubsidyConfigStatusHandler = defineEventHandler(
  async (event) => {
    try {
      const query = getQuery(event);
      const configId = Number.parseInt(query.id as string);
      const body = await readBody(event);

      const configIndex = subsidyConfigs.findIndex(
        (item) => item.configId === configId,
      );
      if (configIndex === -1) {
        return useResponseError('补贴配置不存在');
      }

      // 如果要启用，需要先将同区域类型的其他配置设为停用
      if (body.status === '启用') {
        const targetConfig = subsidyConfigs[configIndex];
        const areaType = targetConfig.areaType;

        // 将同区域类型的其他配置设为停用
        subsidyConfigs.forEach((config) => {
          if (config.areaType === areaType && config.configId !== configId) {
            config.status = '停用';
            config.statusText = '停用';
          }
        });
      }

      subsidyConfigs[configIndex].status = body.status;
      subsidyConfigs[configIndex].statusText =
        body.status === '启用' ? '启用' : '停用';

      return useResponseSuccess({ success: true });
    } catch {
      return useResponseError('更新失败');
    }
  },
);
